/**
 * 动态添加组件
 * @param components 需要加载组件的url 数组 ['','','']
 * @param fun 回调函数
 */

function addComponentUrl(components) {
    const p = new Promise((resolve, reject) => {
        var i = 0;
        for (let item of components) {
            let script = document.createElement('script'),
                head = document.getElementsByTagName('head')[0];
            script.type = 'text/javascript';
            script.charset = 'UTF-8';
            script.onload = script.onreadystatechange = function () {
                if (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") {
                    // 组件的脚本加载完毕，统计加载的数量
                    i++;
                    if (i == components.size()) {
                        resolve();
                    }
                } else {
                    // 存在加载失败的情况
                    reject(script.src);
                }
            };
            script.src = item;
            head.appendChild(script);
        }
    })
    return p;
}

/**
 * 获取唯一标识
 * @returns {string}
 */
function uuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

/**
 * 查询url里的参数
 * @param key
 * @return {*}
 */
function getQuery(key = "") {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == key) {
            return pair[1];
        }
    }
    return (false);
}

window['uuid'] = uuid;
window['getQuery'] = getQuery;

export {
    addComponentUrl, uuid, getQuery
}
